package com.cff.springbootwork.websocket.memory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketSession;

public class WebSocketUser {
	private static Map<String, List<WebSocketSession>> userNameWebsession = new ConcurrentHashMap<>();

	public static void add(String userName, WebSocketSession webSocketSession) {
		userNameWebsession.computeIfAbsent(userName, v -> new ArrayList<WebSocketSession>()).add(webSocketSession);
	}

	/**
	 * 根据昵称拿WebSocketSession
	 * 
	 * @param nickName
	 * @return
	 */
	public static List<WebSocketSession> getSessionByUserName(String userName) {
		return userNameWebsession.get(userName);
	}

	/**
	 * 移除失效的WebSocketSession
	 * 
	 * @param webSocketSession
	 */
	public static void removeWebSocketSession(String userName, WebSocketSession webSocketSession) {
		if (webSocketSession == null)
			return;
		List<WebSocketSession> webSessoin = userNameWebsession.get(userName);
		if (webSessoin == null || CollectionUtils.isEmpty(webSessoin))
			return;
		webSessoin.remove(webSocketSession);
	}
	
	public static Set<String> getUserList(){
		return userNameWebsession.keySet();
	}
}
